package com.sx.micowell.module.personal

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Intent
import android.icu.util.Calendar
import android.text.InputType.*
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.example.mvvm.bar.TitleBar
import com.example.mvvm.base.ContainerActivity
import com.example.mvvm.base.action.TitleBarAction
import com.example.mvvm.base.data.DataBindingConfig
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.Tips
import com.example.mvvm.until.ToastUtils
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.miloyu.modelnet.response.getUrl
import com.sx.micowell.BR
import com.sx.micowell.R
import com.sx.micowell.databinding.FragPersonalInfoBinding
import com.sx.micowell.framework.adapter.binding.EditTextBinding
import com.sx.micowell.framework.app.MyFragment
import com.sx.micowell.framework.arouth.RoutePath
import com.sx.micowell.framework.model.PersonalInfoModel
import com.sx.micowell.framework.tools.FileUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import java.io.File


/**
 * @Author: YY
 * @Time: 2021/8/19
 * @Describe 个人资料
 */
@Route(path = RoutePath.PERSONAL_INFO)
class PersonalInfoFragment : MyFragment<FragPersonalInfoBinding, ContainerActivity>(),
    TitleBarAction {

    lateinit var viewModel: PersonalInfoModel

    private val REQUEST_CODE_CHOOSE_PHOTO_ALBUM = 1

    private var mYear: Int = 0
    private var mMonth: Int = 0
    private var mDay: Int = 0
    lateinit var nameDialog : BasePopupView
    lateinit var sexDialog : BasePopupView
    lateinit var heightDialog : BasePopupView
    lateinit var weightDialog : BasePopupView

    override fun initViewModel() {
        viewModel = getFragmentScopeViewModel(PersonalInfoModel::class.java)
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.frag_personal_info, BR.viewModel, viewModel)
    }

    override fun initView() {
        // 设置状态栏字体颜色
        ImmersionBar.with(this).statusBarDarkFont(true)
            .fitsSystemWindows(true).init()
        binding.title.setOnTitleBarListener(this)
    }

    override fun initData() {
        viewModel.userInfo()

        // 出生年月
        val ca: Calendar = Calendar.getInstance()
        mYear = ca.get(Calendar.YEAR)
        mMonth = ca.get(Calendar.MONTH)
        mDay = ca.get(Calendar.DAY_OF_MONTH)
    }

    @SuppressLint("CheckResult")
    override fun initViewObservable() {
        super.initViewObservable()

        viewModel.nicknameEvent.observe(this, {
            nameDialog=XPopup.Builder(myActivity)
                .autoDismiss(false)
                .asInputConfirm(
                    "昵称", "", "请输入昵称"
                ) { text ->
                    if (text != null && !text.equals("")) {
                        viewModel.modifyUserInfo(
                            "", text,
                            "", "", "", ""
                        )
                        // 昵称
                        binding.sbNickName.rightText = text
                        nameDialog.dismiss()
                    } else {
                        ToastUtils.showShort("请输入昵称")
                    }

                }.show().also {
                    nameDialog=it
                    var editText = it.findViewById<EditText>(R.id.et_input)
                    EditTextBinding.filterEditText(editText, true)
                }
        })

        viewModel.sexEvent.observe(this, {
            XPopup.Builder(myActivity)
                .asBottomList(
                    "请选择性别", arrayOf("男", "女")
                ) { position, text ->

                    if (text != null && !text.equals("")) {
                        viewModel.modifyUserInfo(
                            "", "",
                            position.toString(), "", "", ""
                        )
                    } else {
                        ToastUtils.showShort("请选择性别")
                    }

                }.show()
        })

        viewModel.heightEvent.observe(this, {
            heightDialog=XPopup.Builder(myActivity)
                .autoDismiss(false)
                .asInputConfirm(
                    "身高", "", "请输入身高(cm)"
                ) { text ->
                    if (text != null && !text.equals("")) {
                        viewModel.modifyUserInfo(
                            "", "",
                            "", "", text, ""
                        )
                        heightDialog.dismiss()
                    } else {
                        ToastUtils.showShort("请输入身高")
                    }

                }.show().also {
                    heightDialog = it
                    var editText = it.findViewById<EditText>(R.id.et_input)
                    EditTextBinding.filterEditText(editText, true)
                    editText.inputType = TYPE_CLASS_NUMBER or TYPE_NUMBER_FLAG_DECIMAL
                }
        })

        viewModel.weightEvent.observe(this, {
            weightDialog=XPopup.Builder(myActivity)
                .autoDismiss(false)
                .asInputConfirm(
                "目标体重", "", "请输入目标体重(kg)"
            ) { text ->
                if (text != null && !text.equals("")) {
                    viewModel.modifyUserInfo(
                        "", "",
                        "", "", "", text
                    )
                    weightDialog.dismiss()
                } else {
                    ToastUtils.showShort("目标体重")
                }

            }.show().also {
                weightDialog=it
                var editText = it.findViewById<EditText>(R.id.et_input)
                EditTextBinding.filterEditText(editText, true)
                editText.inputType = TYPE_CLASS_NUMBER or TYPE_NUMBER_FLAG_DECIMAL
            }
        })

        viewModel.birthdayEvent.observe(this, {
            DatePickerDialog(
                mActivity,
                AlertDialog.THEME_HOLO_LIGHT,
                { view, year, month, dayOfMonth ->
                    val text = "${year}-${month}-${dayOfMonth}"
                    viewModel.modifyUserInfo(
                        "", "",
                        "", text, "", ""
                    )
                },
                mYear,
                mMonth,
                mDay
            ).show()
        })

        viewModel.selectHeadersEvent.observe(this, { o ->
            RxPermissions(myActivity)
                .request(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe {
                    if (it) {
                        Matisse.from(this)
                            .choose(MimeType.ofImage())
                            .capture(false)
                            .theme(R.style.Matisse_Dracula)
                            .countable(true)
                            .maxSelectable(1)
                            .imageEngine(GlideEngine())
                            .forResult(REQUEST_CODE_CHOOSE_PHOTO_ALBUM)
                    } else {
                        Tips.showStatus(myActivity, Toast.LENGTH_SHORT, Tips.ERROR, "授权失败")
                    }
                }

        }
        )

        viewModel.userInfoEvent.observe(this, { data ->
            // 头像
            if (TextUtils.isEmpty(data.userPhoto)) {
                binding.imageHead.setImageResource(R.drawable.icon_head_portrait)
            } else {
                Glide.with(this).load(data.userPhoto.getUrl())
                    .apply(RequestOptions.bitmapTransform(CircleCrop()))
                    .placeholder(R.drawable.icon_head_portrait)
                    .into(binding.imageHead)
            }
            // 昵称
            binding.sbNickName.rightText = data.nickname
            // 性别
            binding.sbSex.rightText = if (data.sex == 0) "男" else "女"
            // 生日
            binding.sbBirthday.rightText = data.birthday
            // 身高
            binding.sbHeight.rightText = data.height + "cm"
            // 体重
            binding.sbWeight.rightText = data.weight + "kg"
        })
    }

    override fun getTitleBar(): TitleBar {
        return binding.title
    }

    override fun onLeftClick(v: View?) {
        myActivity.finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_CODE_CHOOSE_PHOTO_ALBUM) {
            if (data == null) return
            val pathList = Matisse.obtainResult(data)
            for (uri in pathList) {
                Glide.with(this).load(uri).into(binding.imageHead)
                LogUtils.d("onActivityResult: $uri")
                // 上传文件
                viewModel.uploadFile(
                    FileUtils.getRealPathFromUri(uri),
                    File(FileUtils.getRealPathFromUri(uri))
                )
            }
        }
    }
}